<template>
  <section class="component distribute-rule">
    <el-card header="设置分配策略">
      <el-form :model="model" :rules="rules" inline label-width="120px" ref="form">
        <el-row>
          <el-form-item label="分配到" prop="distributeType">
            <el-select :disabled="disabledData" clearable placeholder="请选择" v-model="model.distributeType" @change="getCollectionDays">
              <el-option :key="code" :label="name" :value="code" v-for="{ code, name } in $dict.getDictData('DistributeType')"></el-option>
            </el-select>
            <span style="margin-left:10px;font-size:12px">案件池</span>
          </el-form-item>
          <el-form-item label="催收天数" prop="collectionDays" v-if="model.assignModel === 'COLLECTOR' || (casePoolTypes && (casePoolTypes[0]==='WAIT_DISTRIBUTION' || casePoolTypes[0]==='RECOVERED_DISTRIBUTION'))">
            <el-input style="width:150px" placeholder="请输入催收天数" type="number" v-model.trim="model.collectionDays"></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="分配方式" prop="assignModel">
            <el-radio-group :disabled="disabledData" @change="allotTypeChange()" clearable placeholder="请选择" v-if="model.distributeType!=='OUTER'" v-model="model.assignModel">
              <el-radio label="INNER_WAIT_DISTRIBUTION" v-if="casePoolTypes && (casePoolTypes[0]==='WAIT_DISTRIBUTION' || casePoolTypes[0]==='RECOVERED_DISTRIBUTION')">待分配案件池</el-radio>
              <el-radio label="COLLECTOR" v-if="casePoolTypes && casePoolTypes[0]!=='WAIT_DISTRIBUTION' && casePoolTypes[0]!=='RECOVERED_DISTRIBUTION'">按催收员分配</el-radio>
              <el-radio label="DEPARTMENT" v-if="casePoolTypes && casePoolTypes[0]!=='WAIT_DISTRIBUTION' && casePoolTypes[0]!=='RECOVERED_DISTRIBUTION'">按机构分配</el-radio>
              <el-button @click="chooceDepartmentClick()" v-if="model.distributeType && model.assignModel && model.assignModel!=='INNER_WAIT_DISTRIBUTION' && casePoolTypes && casePoolTypes[0]!=='WAIT_DISTRIBUTION' && casePoolTypes[0]!=='RECOVERED_DISTRIBUTION'">选择机构/人员</el-button>
            </el-radio-group>
            <el-radio-group :disabled="disabledData" @change="allotTypeChange()" clearable placeholder="请选择" v-else v-model="model.assignModel">
              <el-radio label="OUTER_WAIT_DISTRIBUTION">分配到委外待分配案件池</el-radio>
              <el-radio label="OUTER_COLLECTING">分配到受托方</el-radio>
              <el-button @click="entrustClick()" v-if="model.assignModel==='OUTER_COLLECTING'">选择受托方</el-button>
            </el-radio-group>
          </el-form-item>
        </el-row>
        <el-row>
          <div style="width:800px;height:100px;border:1px solid #ccc;margin:-20px 0 10px 120px;padding:10px;font-size:12px" v-if="model.assignModel==='DEPARTMENT'&&model.distributeType!=='OUTER'&&model.departmentId">
            <el-row style="margin-top:10px">
              <span style="font-size:12px;margin-right:10px;margin-left:12px">机构：</span>
              <el-cascader :options="departmentData" :props="{value:'id',label:'deptName'}" :show-all-levels="true" change-on-select disabled placeholder style="width: 400px !important" v-model="departmentIds"></el-cascader>
            </el-row>
          </div>
          <div style="width:800px;height:100px;border:1px solid #ccc;margin:-20px 0 10px 120px;padding:10px;font-size:12px" v-if="model.assignModel==='COLLECTOR'&&model.distributeType!=='OUTER'&&model.users&&model.users.length>0">
            <el-row style="margin-bottom:20px;margin-top:10px">
              <span style="font-size:12px;margin-right:10px;margin-left:12px">机构：</span>
              <el-cascader :options="departmentData" :props="{value:'id',label:'deptName'}" :show-all-levels="true" change-on-select disabled placeholder style="width: 400px !important" v-model="departmentIds"></el-cascader>
            </el-row>
            <el-row>
              <el-form-item label="催收员：" prop="sss" style="margin-left:-60px">
                <el-tag :key="tag.id" v-for="tag in model.users">{{tag.realName}}</el-tag>
              </el-form-item>
            </el-row>
          </div>
          <div style="width:800px;height:100px;border:1px solid #ccc;margin:-20px 0 10px 120px;padding:10px;font-size:12px" v-if="model.assignModel==='OUTER_COLLECTING'&&model.distributeType==='OUTER'&&model.entrustData&&model.entrustData.length>0">
            <el-form-item label="受托方:" prop="sss" style="margin-left:-60px">
              <el-tag :key="tag.outsourceId" v-for="tag in model.entrustData">{{tag.outsName}}</el-tag>
            </el-form-item>
          </div>
        </el-row>
        <el-row>
          <el-form-item label="分案策略" prop="distributeMode" v-if="(model.assignModel==='COLLECTOR'||model.assignModel==='OUTER_COLLECTING') && casePoolTypes && casePoolTypes[0]!=='WAIT_DISTRIBUTION' && casePoolTypes[0]!=='RECOVERED_DISTRIBUTION'">
            <el-select v-model="model.distributeMode">
              <el-option label="按金额平均" value="BY_MONEY"></el-option>
              <el-option label="按数量平均" value="BY_NUMBER"></el-option>
              <el-option label="综合分配" value="BY_INTEGRATE"></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="委外到期时间" prop="outEndCycle" v-if="model.distributeType==='OUTER'">
            <el-input :min="0" type="number" v-model="model.outEndCycle"></el-input>
            <span style="margin-left:10px;font-size:12px">天到期</span>
          </el-form-item>
        </el-row>
      </el-form>
    </el-card>
    <!-- 选择受托方 -->
    <el-dialog :close-on-click-modal="false" :show-close="false" :visible.sync="dialog.selectEntrusted" @close="dialog.selectEntrusted = false" @open="$nextTick(()=>$refs['entrusted-case'].refresh())" append-to-body title="选择受托方">
      <entrusted-case :isLawsuit="false" @close="dialog.selectEntrusted=false" @success="successConfirm" ref="entrusted-case"></entrusted-case>
    </el-dialog>
    <!-- 选择机构/人员 -->
    <el-dialog :show-close="false" :visible.sync="dialog.chooseDistribution" @close="dialog.chooseDistribution=false" append-to-body width="800px" @open="$nextTick(()=>$refs['choose-distribution'].getDepartmentData())">
      <choose-distribution :allotType="allotType" :distributeType="model.distributeType" @close="dialog.chooseDistribution=false" @success="distributionConfirm" @successDept="deptConfirm" ref="choose-distribution"></choose-distribution>
    </el-dialog>
  </section>
</template>

<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";
import { Dependencies } from "~/core/decorator";
import { Prop, Emit, Watch, Model } from "vue-property-decorator";
import { Getter, State } from "vuex-class";
import UserSelect from "./user-select.vue";
import EntrustedCase from "./entrusted-case.vue";
import ChooseDistribution from "./choose-distribution.vue";
import { Form } from "element-ui";
import { DISTRIBUTION_TYPE } from "~/config/enum.config";
import { CaseInfoService } from '~/services/domain-service/case-info.service';

@Component({
  components: {
    UserSelect,
    EntrustedCase,
    ChooseDistribution
  }
})
export default class DistributeRule extends Vue {
  @Dependencies(CaseInfoService)
  private CaseInfoService: CaseInfoService;
  @Getter private departmentData;
  @Getter private departmentTreeData;
  @Getter private getAllParentId;
  @State private outSourceList;

  @Model("rule-change", {
    required: true,
    type: Object
  })
  private model: any;

  private days: any = 0;
  // private entrustData: any=[];
  private allotType: any = "";

  @Prop({ type: Boolean }) private disabledData: boolean;
  @Prop({ type: Array })
  private casePoolTypes: any;

  private deptTreeData = [];
  private dialog = {
    // selectUser: false,
    selectEntrusted: false,
    chooseDistribution: false
  };
  private patternCollection = DISTRIBUTION_TYPE;
  private parrentType = 0;

  private rules = {
    collectionDays: { required: true, message: "请输入催收天数" },
    departmentId: { required: true, message: "请选择机构" },
    strategyCaseType: { required: true, message: "请选择分案类型" },
    assignModel: { required: true, message: "请选择分配方式" },
    outsourceId: [{ required: true, message: "请选择受托方", trigger: "blur" }],
    distributeMode: { required: true, message: "请选择分案策略" },
    distributeType: { required: true, message: "请选择分配到的案件池" },
    outEndCycle: [
      { required: true, message: "请输入委外到期时间" },
      { pattern: /^[1-9][0-9]*$/, message: "时间间隔只能为大于0的正整数" }
    ]
  };

  /**
   * 验证表单数据
   */
  public async validate() {
    const form = this.$refs.form as Form;
    const result = await form.validate().catch(() => false);
    let userResult = true;
    if (
      this.model.assignModel === "OUTER_COLLECTING" &&
      !this.model.entrustData.length
    ) {
      this.$message("请选择受托方");
      userResult = false;
    }
    if (this.model.assignModel === "COLLECTOR" && !this.model.users.length) {
      this.$message("请选择分配用户");
      userResult = false;
    }
    if (this.model.assignModel === "DEPARTMENT" && !this.model.departmentId) {
      this.$message("请选择分配机构");
      userResult = false;
    }
    if (result && userResult) {
      this.emitRuleModel(this.model);
      return Promise.resolve();
    } else {
      return Promise.reject("distribute-rule");
    }
  }

  @Emit("rule-change")
  private emitRuleModel(val) { }


  /**
   * 选中的部门数据
   */
  private get departmentIds() {
    return this.getAllParentId(this.model.departmentId);
  }

  private set departmentIds(values) {
    let result = "";
    if (values.length) result = values;
    this.model.departmentId = result;
  }

  /**
   * 切换部门数据源
   */
  private get strategyCaseType() {
    this.deptTreeData = this.departmentTreeData();
    return this.model.strategyCaseType;
  }

  private set strategyCaseType(val) {
    this.model.strategyCaseType = val;
  }

  private getCollectionDays() {
    // 按机构分配不设置催收天数
    if (this.model.assignModel !== 'COLLECTOR' && this.casePoolTypes && this.casePoolTypes[0]!=='WAIT_DISTRIBUTION' && this.casePoolTypes[0]!=='RECOVERED_DISTRIBUTION') return

    this.CaseInfoService.getCollectionDays(this.model.distributeType).subscribe(
      (data) => {
        if (data) {
          this.model.collectionDays = data;
          this.model.limitDays = data;
        }
      });
  }



  private allotTypeChange() {
    this.allotType = this.model.assignModel;
    this.model.entrustData = [];
    this.model.users = [];
    this.departmentIds = [];
    this.getCollectionDays()
  }
  private successConfirm(val: any) {
    this.model.entrustData = val;
    this.model.outsourceIds = val.map(v => v.outsourceId);
    this.dialog.selectEntrusted = false;
  }

  private deptConfirm(val: any) {
    this.model.departmentId = val.id;
    this.getAllParentId(this.model.departmentId);
    this.dialog.chooseDistribution = false;
  }
  private distributionConfirm(val: any, dept) {
    this.model.departmentId = dept.id;
    this.model.users = val.map(v => {
      return {
        id: v.id,
        realName: v.realName
      };
    });
    this.dialog.chooseDistribution = false;
  }

  /**
   * 重置
   */
  private reset() {
    const form: any = this.$refs["form"];
    form.resetFields();
  }
  /**
   * 选择受托方
   */
  private entrustClick() {
    this.dialog.selectEntrusted = true;
  }
  /**
   * 选择机构/人员
   */
  private chooceDepartmentClick() {
    this.dialog.chooseDistribution = true;
  }
}
</script>

<style lang="less" scoped>
.component.distribute-rule {
  .word-pool {
    min-height: 60px;
  }
  .word {
    position: relative;
    min-width: 60px;
    background-color: #f3f3f3;
    padding: 2px 15px 2px 5px;
    border-radius: 3px;
    & ~ {
      margin-right: 10px;
      margin-top: 5px;
    }
    .del-btn {
      display: none;
      position: absolute;
      right: -5px;
      top: -5px;
    }
    &:hover {
      .del-btn {
        display: inline-block;
      }
    }
  }
}
</style>
